import md5 from 'js-md5'

export const HEADER_APPID = 'App-Auth-appid'
export const HEADER_REQURL = 'App-Auth-reqUrl'
export const HEADER_TIMESTAMP = 'App-Auth-timestamp'
export const HEADER_NONCESTR = 'App-Auth-nonceStr'
export const HEADER_SIGN = 'App-Auth-sign'
export const APPID = 'wxxcxappid'
const APPSECRET = 'appsecret'
export const APP_AUTH_ENABLE = true

export const generateSignJson = (reqUrl, timestamp, nonceStr, data) => {
    let params = {
        'appid': APPID,
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'reqUrl': reqUrl,
        'postJsonStr': JSON.stringify(data)
    }
    return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

export const generateSign = (reqUrl, timestamp, nonceStr, data) => {
    let params = {
        'appid': APPID,
        'nonceStr': nonceStr,
        'timestamp': timestamp,
        'reqUrl': reqUrl
    }
    for (let key in data) {
        params[key] = data[key]
    }
    return md5.hex(generateStringFromJsonObj(params) + APPSECRET).toUpperCase()
}

/**
 * 从JSON对象中获取请求需要加密的字符串
 * 如果是
 *  {
 *      a: ['a','b']
 *  }
 * 的数组形式，则转化后为a=a,b，后台对应的也应该是a=a,b的形式
 * @param {*} jsonObj 
 */
export const generateStringFromJsonObj = (jsonObj) => {
    let keys = []
    for (let key in jsonObj) {
        keys.push(key)
    }
    keys.sort()
    let string = ''
    keys.forEach(key => {
		if (jsonObj[key] && (jsonObj[key] + '').trim()) {
			if (string === '') {
				string = string + key + '=' + jsonObj[key]
			} else {
				string = string + '&' + key + '=' + jsonObj[key]
				
			}
		}
    })
    return string
}